package com.lingyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingyi.common.utils.StringUtils;
import com.lingyi.system.domain.MaterialLib;
import com.lingyi.system.domain.Message;
import com.lingyi.system.domain.MessageRecord;
import com.lingyi.system.domain.PublicUser;
import com.lingyi.system.domain.vo.MessageVo;
import com.lingyi.system.mapper.MessageMapper;
import com.lingyi.system.service.IMessageRecordService;
import com.lingyi.system.service.IMessageService;
import com.lingyi.system.service.IPublicUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.fasterxml.jackson.databind.type.LogicalType.Collection;

/**
 * @PackageName: com.lingyi.system.service.impl
 * @ClassName: MessageServiceImpl
 * @Description:
 * @Author: czl
 * @Date: 2025/4/19 23:30
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    private final IMessageRecordService messageRecordService;

    @Override
    public Page selectPage(MessageVo search) {
        LambdaQueryWrapper<Message> queryWrapper = Wrappers.lambdaQuery(Message.class);
        queryWrapper.like(StringUtils.isNotEmpty(search.getContext()), Message::getContext, search.getContext());
        queryWrapper.eq(StringUtils.isNotEmpty(search.getType()), Message::getType, search.getType());

        Page<Message> messagePage = page(search.build(), queryWrapper);

        if (CollectionUtil.isNotEmpty(messagePage.getRecords())) {
            List<Long> messageIds = messagePage.getRecords().stream().map(Message::getId).collect(Collectors.toList());

            List<MessageRecord> messageRecords = messageRecordService.selectByMessageIds(messageIds);

            if (CollectionUtil.isNotEmpty(messageRecords)) {

                Map<Long, List<MessageRecord>> messageRecordMap = messageRecords.stream().collect(Collectors.groupingBy(MessageRecord::getMessageId));

                for (Message record : messagePage.getRecords()) {
                    List<MessageRecord> records = messageRecordMap.getOrDefault(record.getId(), new ArrayList<>());
                    record.setSendSize(records.size());
                }
            }
        }
        return messagePage;
    }
}
